from odbAccess import *
import csv
import os
import shutil

source_folder = '.'  
target_folder = 'result'

if not os.path.exists(target_folder):
    os.makedirs(target_folder)

for filename in os.listdir(source_folder):
    if filename.endswith('.odb'):
        print("converting "+filename+"...")
        source_path = os.path.join(source_folder, filename)
        target_path = os.path.join(target_folder, filename)+".csv"
        
    
        odb_path = source_path  
        odb = openOdb(path=odb_path)


        last_step_name = odb.steps.keys()[-1]
        last_step = odb.steps[last_step_name]
        last_frame = last_step.frames[-1]

        displacement_field = last_frame.fieldOutputs['U']

        csv_file = open(target_path , 'w')
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(['Node Label', 'X Coordinate', 'Y Coordinate', 'Z Coordinate', 'U1 Displacement', 'U2 Displacement', 'U3 Displacement'])  


   
        displacement_field = last_frame.fieldOutputs['U']

        disp=[]
        coord=[]
        for value in displacement_field.values:
            node_label = value.nodeLabel  
            displacement = value.data  
            disp.append([ displacement[0],displacement[1],0])
        
        for instance in odb.rootAssembly.instances.values():
            for node in instance.nodes:
                node_label = node.label
                x, y, z = node.coordinates
                coord.append([node_label,x,y,z])

        for i in range(len(disp)):
            csv_writer.writerow(coord[i]+disp[i])

        csv_file.close()
        odb.close()
        print("done!")